/**
 * Created by Kevin on 2019/8/14.
 */

var sheetConfig = {
    'sectionPerLine' : 4
};

function sheetConvert(sheet)
{
    for (var i=0; i<sheet.data.length; i++)
    {
        var sectionBeats = sheet.data[i].section.split(' ');

        // fill empty item
        while (sectionBeats.length < sheet.beat)
        {
            sectionBeats.push('');
        }
        sheet.data[i].sectionBeats = sectionBeats;
    }

    return sheet;
}

var sheetId = getUrlParam('sheetId') || '';
sheetId = decodeURIComponent(sheetId);
if (!sheetId)
{
    location.href = 'index.html';
}

var musicSheetControl = new Vue({
    el : '#musicSheetControl',
    data : {
        sheet : null,
        sectionPerLine : sheetConfig.sectionPerLine,
        errorInfo : ''
    },
    methods : {
        init : function (){
            var sheetSrc = sheetId;

            if (sheetSrc.indexOf('.') < 0)
            {
                sheetSrc += '.json';
            }

            sheetSrc = 'sheet/' + sheetSrc;

            var me = this;
            $.ajax({
                url : sheetSrc,
                contentType : 'json',
                success : function (result){
                    me.sheet = sheetConvert(result);
                    var title = me.sheet.title || '';
                    if (title)
                    {
                        document.title = me.sheet.title + ' - ' + document.title;
                    }
                },
                error : function (){
                    me.errorInfo = '乐谱加载失败';
                }
            });
        },
        getSectionGroup : function (){
            if (!this.sheet)
            {
                return [];
            }

            var sectionGroup = [];
            var currentLineSectionIndex = 0;
            var tempLine = [];
            var tempSection = null;
            for (var i=0; i<this.sheet.data.length; i++)
            {
                tempSection = this.sheet.data[i];
                tempLine.push(tempSection);
                currentLineSectionIndex++;

                // add line
                if (tempLine.length == sheetConfig.sectionPerLine)
                {
                    sectionGroup.push(tempLine);
                    var tempLine = [];
                }
            }

            // not full section
            if (tempLine.length)
            {
                while (tempLine.length < sheetConfig.sectionPerLine)
                {
                    tempLine.push(null);
                }
                sectionGroup.push(tempLine);
                var tempLine = [];
            }

            return sectionGroup;
        }
    }
});

musicSheetControl.init();
